package com.frejoys.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;

import java.nio.charset.StandardCharsets;
import java.util.Map;

public class JwtUtil {

    public static String createToken(Map<String, Object> map, String secret, Integer exp) {
        map.put("exp", TimeUtil.unixTime() + exp);
        String token = JWTUtil.createToken(map, secret.getBytes(StandardCharsets.UTF_8));
        return token;
    }

    /**
     * 验证token并解析
     * @param token
     * @param secret
     * @return
     */
    public static String verify(String token, String secret, String name) {

        try {
            JWTValidator.of(token).validateDate();
//        } catch (ValidateException e) {
        } catch (Exception e) {
            throw new GeneralException(HttpStatus.tokenExpire);
        }

        boolean b = JWTUtil.verify(token, secret.getBytes(StandardCharsets.UTF_8));

        if (!b) {
            throw new GeneralException(HttpStatus.tokenVerifyFailure);
        }

        JWT jwt = JWTUtil.parseToken(token);

        String value = jwt.getPayload(name).toString();
        if (StrUtil.isEmpty(value)) {
            throw new GeneralException(HttpStatus.tokenInfoError);
        }

        return value;
    }

}
